package com.sxm.yiwei.fragments;


import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sxm.yiwei.R;
import com.sxm.yiwei.activitis.FWContentActivity;
import com.sxm.yiwei.activitis.HomeSearchActivity;
import com.sxm.yiwei.adapters.SearchListviewAdapter;
import com.sxm.yiwei.beans.ShopContent;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * 按距离搜索
 */
public class SearchDistanceFragment extends Fragment {


    private SearchListviewAdapter listviewAdapter;
    public PullToRefreshListView dislistview;
    private int TYPE = 0;
    private HomeSearchActivity homeSearchActivity;
    private SharedPreferences sharedPreferences;
    private String token;
    private String userId;
    private String appId;
    private String longitude;
    private String latitude;
    private int page = 1;
    private String con = null;
     public List<ShopContent.DataBean.ServiceListBean> list = new ArrayList<>();
    public SearchDistanceFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_search_distance, container, false);
        sharedPreferences = getActivity().getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        longitude = sharedPreferences.getString("longitude", "");
        latitude = sharedPreferences.getString("latitude", "");
        dislistview = (PullToRefreshListView) view.findViewById(R.id.searchdis_listview);
        homeSearchActivity = new HomeSearchActivity();
        if (homeSearchActivity.t==null){
            TYPE = 0;
           // con = homeSearchActivity.con;
        }else {
            TYPE = 3;
            //con = homeSearchActivity.t;
        }
        searchService(page);
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden){
            return;
        }else {
            list.clear();
            searchService(page);
        }
    }


    //搜索服务
    public void searchService(int page) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.SHOPSEARCHSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token", token);
        params.addHeader("appId", appId);
        params.addHeader("userId", userId);
        JSONObject object = new JSONObject();
        if(!TextUtils.isEmpty(homeSearchActivity.con)){
            object.put("searchContent", homeSearchActivity.con);
            object.put("pageNo",page+"");
            object.put("pageSize","20");
        }else {}
        object.put("longitude", longitude);
        object.put("latitude", latitude);
        object.put("condition",1);
        params.addParameter("params",object.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                getFWData(result);
                dislistview.onRefreshComplete();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onSuccess: 搜索服务-评价-"+ex);
                dislistview.onRefreshComplete();
                ErrType.errType(getActivity(),ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    // 服务数据
    public void getFWData(String result) {
        Log.d("tag", "getFWData: 服务-1-"+result);

        JSONObject obj1 = JSON.parseObject(result);
        JSONArray data = obj1.getJSONArray("data");
        for (int i = 0; i < data.size(); i++) {
            JSONObject obj2 = JSON.parseObject(String.valueOf(data.get(i)));
            String amount = obj2.getString("amount");
            String distance = obj2.getString("distance");
            String id = obj2.getString("id");
            String name = obj2.getString("name");
            String score = obj2.getString("score");
            String serviceAvatar = obj2.getString("serviceAvatar");
            String volume = obj2.getString("volume");
            DecimalFormat df   = new DecimalFormat("######0.00");
            String ddd = df.format(Double.valueOf(distance));
            ShopContent.DataBean.ServiceListBean serviceListBean = new ShopContent.DataBean.ServiceListBean();
            serviceListBean.setVolume(Integer.valueOf(volume));
            serviceListBean.setServiceAvatar(serviceAvatar);
            if (score==null){
                serviceListBean.setScore(0.0);
            }else {
                serviceListBean.setScore(Double.valueOf(score));
            }
            serviceListBean.setDistance(Double.valueOf(ddd));
            serviceListBean.setAmount(Double.valueOf(amount));
            serviceListBean.setName(name);
            serviceListBean.setId(id);
            list.add(serviceListBean);
        }
        listviewAdapter = new SearchListviewAdapter(getActivity(),list,TYPE);
        dislistview.setAdapter(listviewAdapter);

        dislistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ShopContent.DataBean.ServiceListBean serviceListBean = listviewAdapter.shopList.get(position-1);
                Intent intent =new Intent(getActivity(),FWContentActivity.class);
                intent.putExtra("id",serviceListBean.getId());
                startActivity(intent);

            }
        });
        dislistview.setMode(PullToRefreshBase.Mode.BOTH);
        dislistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (list.size()!=0&&list.size()==20){
                    page++;
                    list.clear();
                    searchService(page);
                }else {
                    list.clear();
                    searchService(page);
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                Log.d("tag", "onPullUpToRefresh: 上");
                if (page!=0&&page==20){
                    page--;
                    list.clear();
                    searchService(page);
                }else {
                    list.clear();
                   searchService(page);
                }
            }
        });
    }

}
